<template>
  <div class="new">
    <div>
      <input
        id="title"
        v-model="meta.title"
        class="title"
        placeholder="请输入标题"
        type="text"
      >
    </div>
    <div class="content-box">
      <textarea
        id="content"
        v-model="meta.content"
        maxlength="5000"
        class="content"
        placeholder="请输入内容"
      />
      <div class="wordlimit">{{ meta.content.length }}/5000</div>
    </div>
    <div class="button-box">
      <button class="submit" @click="submit(1280, 720)">生成横屏</button>
      <button class="submit" @click="submit(720, 1280)">生成竖屏</button>
    </div>

    <div class="upload_contain">
      <el-upload
        ref="upload"
        multiple
        :limit="5"
        action="/textvideo/task/multiTask"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-exceed="handleExceed"
        :file-list="fileList"
        :http-request="uploadFile"
        :auto-upload="false"
      >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 133px;" size="small" type="success" @click="submitUpload">上传到服务器
        </el-button>
        <el-button
          type="primary"
          style="margin-left: 133px;"
          size="small"
          @click="handleRefreh"
        >刷新</el-button>
        <div slot="tip" class="el-upload__tip">支持多文件上传(.txt)</div>
      </el-upload>
    </div>
    <ul>
      <li v-for="(item,key) in vedioList" :key="key">{{ item.data }}</li>
    </ul>

    <div v-loading="loading" class="video-box">
      <video
        v-show="videoJob.videoUrl"
        :src="videoJob.videoUrl"
        controls
      />
    </div>
  </div>
</template>

<script>

import { service } from '@/utils/request'
const RESPONSE_CODE = {
  SUCCSS: 200,
  PROCESSING: 204,
  ERROR: 500,
  VIDEO_SUCCESS: '3',
  VIDEO_FAILD: '4'
}
export default {
  data() {
    return {
      loading: false,
      myHeaders: { 'Content-Type': 'multipart/form-data; boundary=<calculated when request is sent>' },
      meta: {
        title: '',
        content: '',
        processCode: 0,
        process: 0,
        taskId: '',
        response: '',
        rollTimeoutIndex: null
      },
      videoJob: {
        code: null,
        width: 1920,
        height: 1080,
        status: '',
        videoUrl: '',
        rollTimeoutIndex: null
      },
      vedioList: [],
      fileData: '', // 文件上传数据（多文件合一）
      fileList: [], // upload多文件数组
      uploadData: {
        fieldData: {
          id: '' // 机构id,
        }
      },
      refrehList: []
    }
  },
  watch: {
    'videoJob.videoUrl': function() {
      this.loading = false
    }
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    uploadFile(file) {
      this.fileData.append('files', file.file) // append增加数据
    },
    handleRefreh() {
      this.vedioList = []
      this.refrehList.map((item) => {
        service.get(`/textvideo/task/multiTaskProgress/${item}`).then((res) => {
          const { data } = res
          // this.vedioList = Object.getOwnPropertyNames(res.data)
          this.vedioList.push({ data })
          console.log(this.vedioList, data)
        })
      })
    },
    // 上传到服务器
    submitUpload() {
      this.vedioList = []
      // const fieldData = this.uploadData.fieldData  // 缓存，注意，fieldData不要与fileData看混
      const isLt100M = this.fileList.every(file => file.size / 1024 / 1024 < 100)
      if (!isLt100M) {
        this.$message.error('请检查，上传文件大小不能超过100MB!')
      } else {
        this.fileData = new FormData() // new formData对象
        this.$refs.upload.submit() // 提交调用uploadFile函数
        // this.fileData.append('pathId', fieldData.id)  // 添加机构id
        // this.fileData.append('loginToken', this.loginToken)  // 添加token
        service.post('/textvideo/task/multiTask', this.fileData).then((response) => {
          console.log(response)
          if (response.code === 200) {
            this.$message({
              message: '上传成功',
              type: 'success'
            })

            if (response.data && response.data.length > 0) {
              this.refrehList = response.data
              response.data.map((item) => {
                service.get(`/textvideo/task/multiTaskProgress/${item}`).then((res) => {
                  const { data } = res
                  // this.vedioList = Object.getOwnPropertyNames(res.data)
                  this.vedioList.push({ data })
                  console.log(this.vedioList, data)
                })
              })
            }
            this.fileList = []
          } else {
            this.$message({
              message: response.msg,
              type: 'error'
            })
          }
        })
      }
    },

    submit(width, height) {
      this.videoJob.width = width
      this.videoJob.height = height

      clearInterval(this.meta.rollTimeoutIndex)
      this.meta.rollTimeoutIndex = null
      clearInterval(this.videoJob.rollTimeoutIndex)
      this.videoJob.rollTimeoutIndex = null

      this.loading = true
      service
        .post('/textvideo/task/submit', {
          title: this.meta.title,
          content: this.meta.content
        })
        .then(res => {
          if (res.code === RESPONSE_CODE.SUCCSS) {
            this.meta.taskId = res.data.taskId
            this.rollSchedule()
          }
          if (res.code === RESPONSE_CODE.ERROR) {
            this._errorTip('任务提交失败')
          }
        })
        .catch(() => {})
    },

    _errorTip(text) {
      this.$notify.error({
        title: '错误',
        message: text
      })
      this.loading = false
    },

    schedule(taskId) {
      service
        .get(`/textvideo/task/progress/${taskId}`)
        .then(res => {
          console.log(res)
          this.meta.processCode = res.code

          if (res.code === RESPONSE_CODE.SUCCSS) {
            console.log('dakai')
            // this.meta.response = data.data.packageJson
            // this.meta.process = 100
            // window.open(res.data.msg)
            this.videoJob.videoUrl = res.msg
            clearInterval(this.meta.rollTimeoutIndex)
            this.meta.rollTimeoutIndex = null
          } else if (res.code === RESPONSE_CODE.ERROR) {
            // this._errorTip('资源获取失败')
          }
          if (res.code === 204) {
            // this.meta.process = data.data.percent
            this.rollSchedule()
            console.log(111)
          }
        })
        .catch(() => {
          // this._errorTip('资源获取失败')
        })
    },
    rollSchedule() {
      // let outtime = 2000
      // if (!this.meta.rollTimeoutIndex) {
      //   outtime = 0
      // }

      this.meta.rollTimeoutIndex = setTimeout(async() => {
        this.schedule(this.meta.taskId)
      }, 2000)
    }

  }
}
</script>

<style lang="scss" scoped>
.upload_contain{
  margin-top: 20px;
}
ul {
               list-style:none;
}

.new {

  box-sizing: border-box;
  padding: 10px;
  display: flex;
  flex-direction: column;

  .title,
  .content {
    width: 100%;
    box-sizing: border-box;
    font-size: 14px;
    padding: 5px;
    border-radius: 4px;
    line-height: 1.2em;
    border: 1px solid #c4c4c4;
    outline: none;
  }
  .content-box {
    position: relative;

    .content {
      margin-top: 10px;
      min-height: 200px;
    }

    .wordlimit {
      position: absolute;
      bottom: 20px;
      right: 20px;
      color: #818181;
    }
  }

  .button-box {
    display: flex;
  }
  .submit {
    flex: 1 1 auto;
    background-color: rgb(49, 98, 233);
    border-radius: 4px;
    color: #fff;
    font-size: 20px;
    padding: 4px;
    margin: 0 10px;
    border: none;
    cursor: pointer;
  }
  .video-box {
    display: flex;
    justify-content: center;
    flex: 1 1 auto;
    height: 500px;
    padding: 10px;

    video {
      height: 100%;
      box-shadow: 3px 2px 7px #777;
    }
  }
}
</style>
